#!/bin/bash

# 默认值
project_folder=""
skip_folders=()
output_path="frameworks.json"

# 解析参数
while [[ $# -gt 0 ]]; do
    key="$1"
    case $key in
        -project)
            project_folder="$2"
            shift
            shift
            ;;
        -skip)
            shift
            while [[ $# -gt 0 && ! $1 == -* ]]; do
                skip_folders+=("$1")
                shift
            done
            ;;
        -o)
            output_path="$2"
            shift
            shift
            ;;
        -h)
            echo "帮助文档："
            echo "-project <project文件夹> : 指定项目文件夹"
            echo "-skip <文件夹1 文件夹2 ...> : 指定要跳过的文件夹数组"
            echo "-o <输出路径> : 指定输出路径，默认为 frameworks.json"
            echo "-h : 显示帮助文档"
            exit 0
            ;;
        *)
            echo "未知参数: $1"
            exit 1
            ;;
    esac
done

# 检查必要参数
if [[ -z $project_folder ]]; then
    echo "请指定项目文件夹"
    exit 1
fi

# 扫描Swift文件并记录Framework信息
frameworks=()
while IFS= read -r -d '' file; do
    skip=false
    for skip_folder in "${skip_folders[@]}"; do
        if [[ $file == *"$skip_folder"* ]]; then
            skip=true
            break
        fi
    done

    if [[ $skip == false ]]; then
        frameworks+=($(grep -oE 'import\s+[A-Za-z0-9_]*' "$file" | awk '{print $2}'))
    fi
done < <(find "$project_folder" -type f -name "*.swift" -print0)

# 去重并排序
frameworks=($(echo "${frameworks[@]}" | tr ' ' '\n' | sort -u | tr '\n' ' '))

# 生成JSON文件
json="{\"frameworks\": ["
for framework in "${frameworks[@]}"; do
    json+="\"$framework\", "
done
json="${json%, }"
json+="]}"

# 写入JSON文件
echo "$json" | jq '.' > "$output_path"

echo "已将Framework信息写入 $output_path 文件"